package controller

import (
	"YingShop/entity"
	"YingShop/log"
	outerapi "YingShop/outerApi"
	querystruct "YingShop/queryStruct"
	"fmt"
	"strconv"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type ShopUserController struct {
	Result
}

func (userController ShopUserController) Get(ctx *gin.Context) {
	userId, _ := strconv.Atoi(ctx.Param("userId"))
	loginUserId, ok := ctx.Keys["userId"].(int)
	if !ok {
		userController.RetCode = 401
		userController.Msg = "请先登录"
		ctx.JSON(401, userController.Result)
		return
	}
	if userId != loginUserId {
		userController.RetCode = -1
		userController.Msg = "只能查询自己的用户信息"
		ctx.JSON(401, userController.Result)
		return
	}
	shopUser := entity.ShopUser{UserId: int(userId)}
	err := shopUser.Load()
	if err != nil {
		userController.RetCode = -1
		userController.Msg = err.Error()
		ctx.JSON(200, userController.Result)
	} else {
		userController.RetCode = 0
		userController.Msg = "success"
		userController.Data = gin.H{
			"userName":    shopUser.UserName,
			"phoneNumber": shopUser.PhoneNumber,
			"userId":      shopUser.UserId,
		}
		ctx.JSON(200, userController.Result)
	}
}

func (userController ShopUserController) Login(ctx *gin.Context) {
	loginParam := querystruct.UserLoginParam{}
	err := ctx.BindJSON(&loginParam)
	if err != nil {
		log.Error(fmt.Sprintf("登录失败:%s", err))
		userController.RetCode = -1
		userController.Msg = "登录失败，请稍后重试"
		ctx.JSON(200, userController.Result)
		return
	}
	UserInfo := entity.ShopUser{UserId: loginParam.UserId, PhoneNumber: loginParam.PhoneNumber}
	err = UserInfo.Load()
	if err != nil {
		log.Error(fmt.Sprintf("登录失败:%s", err))
		userController.RetCode = -1
		userController.Msg = "登录失败，请稍后重试"
		ctx.JSON(200, userController.Result)
		return
	}
	session := sessions.Default(ctx)
	session.Set("userName", UserInfo.UserName)
	session.Set("userId", UserInfo.UserId)
	err = session.Save()
	if err != nil {
		log.Error(fmt.Sprintf("登录失败:%s", err))
		userController.RetCode = -1
		userController.Msg = "登录失败，请稍后重试"
		ctx.JSON(200, userController.Result)
		return
	}
	userController.RetCode = 0
	userController.Msg = "success"
	userController.Data = gin.H{
		"userId": UserInfo.UserId,
	}
	ctx.JSON(200, userController.Result)
}

func (userController ShopUserController) WxLogin(ctx *gin.Context) {
	loginParam := querystruct.WxLoginParam{}
	err := ctx.BindJSON(&loginParam)
	if err != nil {
		log.Error(fmt.Sprintf("登录失败:%s", err))
		userController.RetCode = -1
		userController.Msg = "登录失败，请稍后重试"
		ctx.JSON(200, userController.Result)
		return
	}
	wxApi := outerapi.WxAppApi{Appid: "wx5e89cd353842bc84", Secret: "7bd4378826ae5f42bbba3d9a0e6a7ed3"}
	loginRes := wxApi.Code2Session(loginParam.LoginCode)
	log.Info(fmt.Sprintf("wx登录校验结果%v", loginRes))
	openid := loginRes.Openid
	UserInfo := entity.ShopUser{WxOpenId: openid}
	err = UserInfo.LoadByWxOpenId()
	if err != nil {
		log.Error(fmt.Sprintf("登录失败:%s", err))
		userController.RetCode = -1
		userController.Msg = "登录失败，请稍后重试"
		ctx.JSON(200, userController.Result)
		return
	}
	session := sessions.Default(ctx)
	session.Set("userName", UserInfo.UserName)
	session.Set("userId", UserInfo.UserId)
	session.Set("wxSessionKey", loginRes.SessionKey)
	session.Set("wxUnionId", loginRes.Unionid)
	err = session.Save()
	if err != nil {
		log.Error(fmt.Sprintf("登录失败:%s", err))
		userController.RetCode = -1
		userController.Msg = "登录失败，请稍后重试"
		ctx.JSON(200, userController.Result)
		return
	}
	userController.RetCode = 0
	userController.Msg = "success"
	userController.Data = gin.H{
		"userId": UserInfo.UserId,
	}
	ctx.JSON(200, userController.Result)
}

func (userController ShopUserController) WxRegist(ctx *gin.Context) {
	registParam := querystruct.WxRegistParam{}
	err := ctx.BindJSON(&registParam)
	if err != nil {
		log.Error(fmt.Sprintf("注册失败:%s", err))
		userController.RetCode = -1
		userController.Msg = "注册失败，请稍后重试"
		ctx.JSON(200, userController.Result)
		return
	}
	wxApi := outerapi.WxAppApi{Appid: "wx5e89cd353842bc84", Secret: "7bd4378826ae5f42bbba3d9a0e6a7ed3"}
	loginRes := wxApi.Code2Session(registParam.LoginCode)
	log.Info(fmt.Sprintf("wx登录校验结果%v", loginRes))
	openid := loginRes.Openid
	UserInfo := entity.ShopUser{WxOpenId: openid, UserName: registParam.UserName, PhoneNumber: registParam.UserPhoneNumber}
	err = UserInfo.Register()
	if err != nil {
		log.Error(fmt.Sprintf("注册失败:%s", err))
		userController.RetCode = -1
		userController.Msg = "注册失败，请稍后重试"
		ctx.JSON(200, userController.Result)
		return
	}
	session := sessions.Default(ctx)
	session.Set("userName", UserInfo.UserName)
	session.Set("userId", UserInfo.UserId)
	session.Set("wxSessionKey", loginRes.SessionKey)
	session.Set("wxUnionId", loginRes.Unionid)
	err = session.Save()
	if err != nil {
		log.Error(fmt.Sprintf("登录失败:%s", err))
		userController.RetCode = -1
		userController.Msg = "登录失败，请稍后重试"
		ctx.JSON(200, userController.Result)
		return
	}
	userController.RetCode = 0
	userController.Msg = "success"
	userController.Data = gin.H{
		"userId": UserInfo.UserId,
	}
	ctx.JSON(200, userController.Result)
}

func (userController ShopUserController) GetOrderList(ctx *gin.Context) {
	session := sessions.Default(ctx)
	userId, _ := session.Get("userId").(int)
	user := entity.ShopUser{UserId: userId}
	orderList, err := user.GetUserOrderList()
	if err != nil {
		userController.RetCode = -1
		userController.Msg = err.Error()
		ctx.JSON(200, userController.Result)
		return
	}
	userController.RetCode = 0
	userController.Msg = "success"
	userController.Data = gin.H{
		"orderList": orderList,
	}
	ctx.JSON(200, userController.Result)
}
